<template>
  <el-dialog
    v-model="centerDialogVisible"
    :title="t('dbms.microservices.config.uploadConfigTitle')"
    align-center
    width="800px"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-scrollbar height="600">
      <br />
      <el-timeline style="max-width: 600px">
        <el-timeline-item
          v-for="(appServer, index) in appServers"
          :key="index"
          style="max-height: 100%"
        >
          <div class="item">
            {{ appServer.ip + ':' + appServer.port }}
            <el-tag v-if="appServer.state == 0" type="info" size="small">等待更新</el-tag>
            <el-tag v-if="appServer.state == 1" type="primary" size="small">开始更新</el-tag>
            <el-tag v-if="appServer.state == 2" type="success" size="small">完成更新</el-tag>
            <el-tag v-if="appServer.state == 3" type="danger" size="small">更新失败</el-tag>
          </div>
          <div v-if="appServer.state == 3" class="error-message">
            <el-scrollbar height="100px">
              <pre>{{ appServer.msg }}</pre>
            </el-scrollbar>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-scrollbar>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { listAppServerApi } from '@/api/dbms/appserver'
import { activeApi, uploadApi } from '@/api/dbms/appconfig'
import { ElMessage } from 'element-plus'

const centerDialogVisible = ref(false)

const { t } = useI18n()

const configId = ref('')

const appServers = ref()

const loadAppServer = async (appName: string) => {
  const rs = await listAppServerApi({ appName })
  if (rs.success) {
    appServers.value = rs.data
    appServers.value.forEach((el) => {
      el['state'] = 0
    })

    uploadConfig(0)
  }
}

const show = (cId: string, appName: string) => {
  configId.value = cId
  loadAppServer(appName)
  centerDialogVisible.value = true
}

//上传配置
const uploadConfig = async (index: number) => {
  if (index >= appServers.value.length) {
    const rs = await activeApi({ id: configId.value })
    if (rs.success) {
      ElMessage.success(rs.message)
    }
  } else {
    const appServer = appServers.value[index]
    appServer.state = 1
    const rs = await uploadApi({ configId: configId.value, appServerId: appServer.id })
    if (rs.success) {
      if (rs.data) {
        appServer.state = 3
        appServer.msg = rs.data
      } else {
        appServer.state = 2
      }
      const lastIndex = index + 1
      uploadConfig(lastIndex)
    }
  }
}

//关闭表单
const hide = () => {
  centerDialogVisible.value = false
}

//暴露方法
defineExpose({ show, hide })
</script>
